package com.largeOrange.filter;

import com.alibaba.fastjson.JSON;
import com.largeOrange.common.IdThreadLocal;
import com.largeOrange.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

/**
 * @author 大橙子
 * @version 1.0
 * @since 1.0
 */
@Slf4j
@WebFilter(filterName = "checkFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //字符串路劲匹配
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //定义不需要被拦截的String数组
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        //获取请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求...");
        //开始匹配
        boolean checkUrl = checkUrl(urls, requestURI);
        //如果存在不需要拦截的路径，则放行
        if (checkUrl){
            log.info("合法请求通过...");
            filterChain.doFilter(request,response);
            return;
        }
        //不包含，判断是否登录过
        Long id = ((Long) request.getSession().getAttribute("employee"));
        if (id!=null){
            log.info("已登录请求通过...");
            IdThreadLocal.setId(id);
            System.out.println("过滤器----------->>"+IdThreadLocal.getId()+"线程----》"+Thread.currentThread().getName());
            filterChain.doFilter(request,response);
            return;
        }
        //没登陆过
        log.info("未登录请求拦截...");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 定义路径匹配方法
     * @param urls
     * @param url
     * @return
     */
    public boolean checkUrl(String[] urls,String url){
        for (String onUrl : urls) {
            boolean match = PATH_MATCHER.match(onUrl, url);
            if (match){
                return true;
            }
        }
        return false;
    }
}
